package com.community.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.community.dto.StorageGatherDto;
import com.community.pojo.*;
import com.community.service.*;
import com.community.utils.NumberUtils;
import com.community.utils.PageUtils;
import com.community.vo.GatherVo;
import com.community.vo.StorageGatherTwoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TangHaoSong Fly ChenJie HeYuHang
 * @since 2024-05-15
 */
@CrossOrigin
@Controller
@RequestMapping("/community/gather")
public class GatherController {

    @Autowired
    private IGatherService gatherService;

    @Autowired
    private IPurchaseOrderService purchaseOrderService;

    @Autowired
    private IStockService stockService;

    @Autowired
    private IStockDetailsService stockDetailsService;

    @Autowired
    private IPurchaseOrderDetailsService purchaseOrderDetailsService;

    @Autowired
    private IGatherDetailsService gatherDetailsService;

    @Autowired
    private NumberUtils numberUtils;

    /**
     * 入库申请登记
     * @param
     * @return
     */
//    @RequestMapping("/add")
//    @ResponseBody
//    public String add(@RequestBody StorageGatherDto dto) {
//        // 生成入库设计单编号
//        String typeNumber = numberUtils.getTypeNumber("200");
//        dto.setGatherId(typeNumber);
//        dto.setCheckTag("S001-3");
//        BigDecimal num = new BigDecimal(0);
//        dto.setTotalAmount(num);
//        gatherService.page1(dto);
//        return "ok";
//    }
//    @RequestMapping("/add")
//    @ResponseBody
//    public String add(@RequestBody StorageGatherDto dto) {
//        // 生成入库设计单编号
//        String typeNumber =numberUtils.getTypeNumber2("200"); // 将字符串转换为整数
//        dto.setGatherId(typeNumber);
//        dto.setCheckTag("S001-3");
//        BigDecimal num = new BigDecimal(0);
//        dto.setTotalAmount(num);
//        gatherService.page1(dto);
//        return "ok";
//    }
    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestBody StorageGatherDto storageGatherDto) {
        System.out.println("gather++++"+storageGatherDto);

        //制定入库单
        Gather gather1 = new Gather();
        // 生成入库设计单编号
        String typeNumberStr = numberUtils.getTypeNumber("200");
        gather1.setGatherOrderNumber(typeNumberStr);
        //入库id
        gather1.setGatherId(null);
        //设置审核标准:S001-1 等待审核
        gather1.setCheckTag("S001-1");
        //设置总数量
        BigDecimal num = new BigDecimal(0);
        num = storageGatherDto.getGather().getTotalAmount();
        gather1.setTotalAmount(num);
        //总价格
        gather1.setTotalPrice(storageGatherDto.getGather().getTotalPrice());
        //入库人
        gather1.setStorer(storageGatherDto.getGather().getStorer());
        // 入库理由
        gather1.setReason(storageGatherDto.getGather().getReason());
        //采购id
        gather1.setPurchaseId(storageGatherDto.getGather().getPurchaseId());

        //添加入库单
        gatherService.save(gather1);
        int gatherId = gather1.getGatherId();
        int supplierId = storageGatherDto.getGather().getSupplierId();
        List<PurchaseOrderDetails> details = storageGatherDto.getDetails();
        for (int i = 0;i<details.size();i++){
            GatherDetails gatherDetails = new GatherDetails();
            //入库明细id
            gatherDetails.setId(null);
            //入库单id
            gatherDetails.setGatherId(gatherId);
            //商品id
            gatherDetails.setProductId(details.get(i).getProductId());
            //供应商id
            gatherDetails.setSupplierId(supplierId);
            //数量
            gatherDetails.setAmount(new BigDecimal(details.get(i).getCount()) );
            //单价
            gatherDetails.setPrice(new Double(details.get(i).getPrice()));
            //小计
            gatherDetails.setSubTotal(new Double(details.get(i).getSubtotal()));

            gatherDetailsService.save(gatherDetails);
        }
        return "ok";
    }

    @RequestMapping("/updateById")
    @ResponseBody
    public String updateById(int id) {
//        System.out.println(id);
        PurchaseOrder purchaseOrder = this.purchaseOrderService.getById(id);
        //将采购单入库标志改为已收货,配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
        purchaseOrder.setConveyTag("P001-3");
        purchaseOrderService.updateById(purchaseOrder);
        return "ok";
    }
    @RequestMapping("/update")
    @ResponseBody
    public String update(@RequestBody Stock stock) {
        System.out.println("stock++++"+stock);

        // 获取当前库存对象
        Stock currentStock = stockService.getById(stock.getStockId());
        int currentAmount = currentStock.getAmount();
        int increaseAmount = stock.getAmount();
        int newAmount = currentAmount + increaseAmount;

        // 更新库存对象
        currentStock.setAmount(newAmount);
        stockService.updateById(currentStock);
        return "ok";
    }
//    //制定入库明细单
//    @RequestMapping("/addDetails")
//    @ResponseBody
//    public String addDetails(int purchaseId,@RequestBody List<PurchaseOrderDetails> purchaseOrderDetails){
//        System.out.println("purchaseOrderDetails++++"+purchaseOrderDetails);
//        PurchaseOrderDetails purchaseOrderDetails1 = new PurchaseOrderDetails();
//        //入库id
//        purchaseOrderDetails1.setId(null);
//        //入库单id
//        return "ok";
//    }
    /**
     * 入库单表查询
     */
    @RequestMapping("/gatherList")
    @ResponseBody
    public List<Gather> gatherList() {
        List<Gather> list = gatherService.list();
        return list;
    }
    /**
     * 入库单表查询
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/show/{currentPage}/{pageSize}")
    public PageUtils<Gather> show(@PathVariable int currentPage,
                                 @PathVariable  int pageSize) {
        QueryWrapper<Gather> qw = new QueryWrapper<Gather>();
        //审核状态  等待审核
        qw.eq("CHECK_TAG", "S001-1");
        PageHelper.startPage(currentPage, pageSize);
        List<Gather> list = gatherService.list(qw);
        PageInfo<Gather> p = new PageInfo<Gather>(list);
        PageUtils<Gather> utils = new PageUtils<Gather>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 入库单审核
     * @param vo
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/showtongguo/{currentPage}/{pageSize}")
    public PageUtils<Gather> showtongguo(@RequestBody GatherVo vo, @PathVariable int currentPage, @PathVariable int pageSize) {
        QueryWrapper<Gather> qw = new QueryWrapper<Gather>();
        if (vo != null) {
            if (!StringUtils.isEmpty(vo.getSearch_gatherId())) {
                qw.eq("gather_id", vo.getSearch_gatherId());
            }
            if (!StringUtils.isEmpty(vo.getSearch_storer())) {
                qw.like("storer", vo.getSearch_storer());
            }
            if (!StringUtils.isEmpty(vo.getSearch_register())) {
                qw.like("register", vo.getSearch_register());
            }
            if (!StringUtils.isEmpty(vo.getSearch_checkTime1())) {
                qw.ge("check_time", vo.getSearch_checkTime1());
            }
            if (!StringUtils.isEmpty(vo.getSearch_checkTime2())) {
                qw.le("check_time", vo.getSearch_checkTime2());
            }
        }
        qw.eq("CHECK_TAG", "S001-1");
        PageHelper.startPage(currentPage, pageSize);
        List<Gather> list = gatherService.list(qw);
        PageInfo<Gather> p = new PageInfo<Gather>(list);
        PageUtils<Gather> utils = new PageUtils<Gather>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 入库审核查询  带分页
     * @return
     */
    @RequestMapping("/ShowAudit/{currentPage}/{pageSize}")
    @ResponseBody
    public PageUtils<Gather> updateAudit(@PathVariable int currentPage, @PathVariable int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Gather> list = gatherService.list();
        PageInfo<Gather> p = new PageInfo<Gather>(list);
        PageUtils<Gather> utils = gatherService.updateAudit();

        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 入库审核查询  带分页  双表查询
     * @return
     */
    @RequestMapping("/ShowAudit2/{currentPage}/{pageSize}")
    @ResponseBody
    public PageUtils<Gather> updateAudit2(@PathVariable int currentPage, @PathVariable int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<Gather> list = gatherService.list();
        PageInfo<Gather> p = new PageInfo<Gather>(list);
        PageUtils<Gather> utils = gatherService.updateAudit();

        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 审核通过
     * @param gather
     * @return
     */
    @ResponseBody
    @RequestMapping("/update3")
    public boolean update(@RequestBody Gather gather) {
        gather.setCheckTag("S001-3");
        boolean b = gatherService.updateById(gather);
        return b;
    }
    /**
     * 根据id查询所有入库的
     * @param gatherId
     * @return
     */
    @RequestMapping("/showById")
    @ResponseBody
    public Gather showById(Integer gatherId) {
        Gather byId = gatherService.getById(gatherId);
        return byId;
    }
    /**
     * 修改入库单
     * @param gather
     * @return
     */
//    @RequestMapping("/updateById")
//    @ResponseBody
//    public String updateById(@RequestBody Gather gather) {
//        boolean b = gatherService.updateById(gather);
//        if(b){
//            return "ok";
//        }
//        return "error";
//    }
    /**
     * 删除
     * @param gatherId
     * @returnID
     */
    @ResponseBody
    @RequestMapping("/del")
    public boolean del(int gatherId) {
        boolean b = gatherService.removeById(gatherId);
        return b;
    }
    /**
     * 添加入库单
     * @param gather
     * @return
     */
    @ResponseBody
    @RequestMapping("/addGather")
    public Boolean addGather(@RequestBody Gather gather) {
        boolean save = gatherService.save(gather);
        return save;
    }
    /**
     * 双表查询
     * @param gatherId
     * @return
     */
    @ResponseBody
    @RequestMapping("/gatherID")
    public Gather GatherID(Integer gatherId) {
        QueryWrapper<Gather> qw = new QueryWrapper<Gather>();
        qw.eq("gather_id", gatherId);
        Gather one = gatherService.getOne(qw);
        return one;
    }
    /**
     * 采购单查询,已发货,待入库
     * @param
     * @return
     */
    @RequestMapping("/purchaseOrderList/{currentPage}/{pageSize}")
    @ResponseBody
    public PageUtils<PurchaseOrder> purchaseOrderList(@PathVariable int currentPage,
                                                      @PathVariable  int pageSize) {
        PageHelper.startPage(currentPage, pageSize);
        List<PurchaseOrder> list = purchaseOrderService.purchaseOrderList();
        PageInfo<PurchaseOrder> p = new PageInfo<>(list);
        PageUtils<PurchaseOrder> utils = new PageUtils<>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    @RequestMapping("/purchaseOrderList2/{currentPage}/{pageSize}")
    @ResponseBody
    public PageUtils<PurchaseOrder> purchaseOrderList2(@PathVariable int currentPage,
                                                      @PathVariable  int pageSize) {
        QueryWrapper<PurchaseOrder> wrapper = new QueryWrapper<>();
        wrapper.eq("check_tag","S001-3");
        wrapper.eq("gather_tag","K001-1");
        wrapper.eq("convey_tag","P001-2");
        PageHelper.startPage(currentPage, pageSize);
        List<PurchaseOrder> list = purchaseOrderService.list(wrapper);
        PageInfo<PurchaseOrder> p = new PageInfo<>(list);
        PageUtils<PurchaseOrder> utils = new PageUtils<>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 根据id查询所有采购单
     * @param purchaseId
     * @return
     */
    @RequestMapping("/showById2")
    @ResponseBody
    public PurchaseOrder showById2(int purchaseId) {
        PurchaseOrder byId = purchaseOrderService.getById(purchaseId);
        return byId;
    }
    /**
     * 制定入库单表格里面的数据
     * @param
     * @return
     */
    @RequestMapping("/purchaseOrderById")
    @ResponseBody
    public List<PurchaseOrderDetails> PurchaseOrderById(int id) {
        QueryWrapper<PurchaseOrderDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("purchase_id",id);
        List<PurchaseOrderDetails> list = this.purchaseOrderDetailsService.list(wrapper);
        return list;
    }
    /**
     * 入库调库表格里面的数据
     * @param
     * @return
     */
    @RequestMapping("/gatherById")
    @ResponseBody
    public List<GatherDetails> gatherById(int id) {
        QueryWrapper<GatherDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("gather_id",id);
        List<GatherDetails> list = this.gatherDetailsService.list(wrapper);
        System.out.println("kk++++"+list);
        return list;
    }
    /**
     * 已审核,已登记
     * @param vo
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/twoShow2/{currentPage}/{pageSize}")
    @ResponseBody
    public PageUtils<Gather> twoShow2(StorageGatherTwoVo vo,@PathVariable int currentPage,@PathVariable int pageSize) {
        PageUtils<Gather> show = gatherService.twoShow(vo, currentPage, pageSize);
        return show;
    }
    /**
     * 入库调库表格里面的数据
     * @param gatherId
     * @return
     */
    @RequestMapping("/gatherDetailsById")
    @ResponseBody
    public PageUtils<GatherDetails> GatherDetailsById(Integer gatherId) {
        QueryWrapper<GatherDetails> qw = new QueryWrapper<>();
        // 将查询条件上的左引号放置在参数名后面
        qw.eq("gather_id", gatherId);
        List<GatherDetails> list = gatherDetailsService.list(qw);
        PageInfo<GatherDetails> p = new PageInfo<>(list);
        PageUtils<GatherDetails> utils = new PageUtils<>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 入库调库表格里面的数据
     * @param
     * @return
     */
    @RequestMapping("/gatherDetailsById2")
    @ResponseBody
    public PageUtils<GatherDetails> GatherDetailsById2() {
        List<GatherDetails> list = gatherDetailsService.list();
        PageInfo<GatherDetails> p = new PageInfo<>(list);
        PageUtils<GatherDetails> utils = new PageUtils<>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 入库调度按钮
     * @param stockId
     * @param gatheredAmount
     * @return
     */
    @RequestMapping("/updateTWO")
    @ResponseBody
    public boolean updateTWO(Integer stockId, Integer gatheredAmount) {
        GatherDetails s = new GatherDetails();
        s.setId(stockId);
        BigDecimal b = new BigDecimal(gatheredAmount);
        s.setAmount(b);
        //s.set("K002-2");
        boolean b1 = gatherDetailsService.updateById(s);
        return b1;
    }
    /**
     * 入库调度
     * @param stockId
     * @param totalAmount
     * @return
     */
    @RequestMapping("/updateTWO2")
    @ResponseBody
    public boolean updateTWO2(Integer stockId, Integer totalAmount) {
        GatherDetails s = new GatherDetails();
        s.setId(stockId);
        BigDecimal b = BigDecimal.ZERO; // 默认值为0
        if (totalAmount != null) {
            b = BigDecimal.valueOf(totalAmount);
        }
        s.setAmount(b);
//        Integer b = 0; // 默认值为0
//        if (totalAmount != null) {
//            b = totalAmount;
//            s.setAmount(b);
//        }
        boolean result = gatherDetailsService.updateById(s);
        return result;
    }



}
